<?

class front_controller
{
	protected static $application;
	protected static $action;

	public static function run( $application = 'main' )
	{
		self::$application = $application;
		self::$action = request::get_action();

		$class = self::$action . '_action';
		if ( !class_exists($class) )
		{
			self::$action .= '_index';
			$class = self::$action . '_action';
		}

		self::dispatch_action($class);
	}

	public static function dispatch_action( $class )
	{
		if ( !class_exists($class) )
		{
			header('Status: 404 Not Found');
			$p404 = PROJECT_PATH . '/apps/' . front_controller::get_application() . '/layout/404.php';
			if ( !is_file($p404) )
				echo 'Nothings here';
			else
				include $p404;
			exit;
		}

		self::dispatch( new $class );
	}

	public static function dispatch( action_controller $controller )
	{
		if ( config::get('pause') )
		{
			$p404 = PROJECT_PATH . '/apps/' . front_controller::get_application() . '/layout/pause.php';
			if ( !is_file($p404) )
				echo 'Cofee break for 5 minutes';
			else
				include $p404;

			return;
		}

		context::set('action', $controller);

		$controller->init();
		if ( config::get('debug') ) debug::timer_continue('Action init');

		$controller->execute();
		if ( config::get('debug') ) debug::timer_continue('Action execute');

		$methodExecuter = 'execute' . ( request::get_method() == 'POST' ? '_post' : '_get' );
		$controller->$methodExecuter();

		$controller->finalize();
		if ( config::get('debug') ) debug::timer_continue('Action finalize');

		$body = render::action($controller);
		if ( config::get('debug') ) debug::timer_continue('Action render');

		response::set_body( $body );
		response::send();

		if ( config::get('debug') && ($controller->get_renderer() == 'html') && $controller->get_layout() )
			echo render_html::render_partial('debug');

		if ( config::all()->ssi['enable'] ) ssi::store( $body );
	}

	public static function get_application()
	{
		return self::$application ? self::$application : 'main';
	}
}